{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(size_layer = size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.BahdanauMonotonicAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse=reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_out = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_out,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_out = tf.concat((out_fw, out_bw), 2)\n",
    "        bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n",
    "        bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n",
    "        bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n",
    "        encoder_state = tuple([bi_lstm_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-18535ee545eb>:12: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-18535ee545eb>:40: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:958: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:962: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-18535ee545eb>:19: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[20372, 20372, 15834, 14405, 14405, 14405, 14405, 10244, 10244,\n",
       "         10244, 10244, 10244, 24771, 24771, 10096, 10096, 10096, 10096,\n",
       "         24888, 24888, 24888, 16804, 16804, 16804, 16804, 16804, 16917,\n",
       "         16917, 16917, 16917, 19714, 19714, 19714, 28672, 13731, 13731,\n",
       "          5701,  5701,  5701,  5701,  5701,   860,   860,   860,   860,\n",
       "          4793,  4793, 10030,  1070, 12616, 12616, 12616, 13252, 10138,\n",
       "         10138, 10138, 10138, 10138,  7635, 17461, 17461, 17461, 17461,\n",
       "         17461, 17461, 17461, 31189, 31189, 31189,  2948,  4772,  4772],\n",
       "        [ 7216, 27528, 24472, 24472, 24472, 24472, 28258, 25162, 25162,\n",
       "         25162, 25162, 14137, 14137, 14137, 14137, 14137, 15247, 15247,\n",
       "          8013,  8013,  8013,  7063, 10535, 12755, 12755, 12755, 28844,\n",
       "         24636, 24636, 24636, 21346, 21346, 31382, 31382, 31382, 31382,\n",
       "         26176, 26600, 26600, 26600, 26600, 26600, 23550, 23550, 25697,\n",
       "         25697, 25697, 25697,  9554,  9554,  9554,  9554,  9554,  1896,\n",
       "         28503, 28503,  1896, 28503, 28503, 28503,  7364, 31797, 31797,\n",
       "         31797, 31797, 31797, 14821, 14821, 14821, 18362,  6788,  6788],\n",
       "        [10991, 10991, 17967, 17967, 17967, 17967, 17967, 26016, 26016,\n",
       "         26016, 26016, 26016,  1136,  1136,  1136, 10658, 10658, 10658,\n",
       "         10658, 20307,  3247,  3247,  3247,  3247, 22276, 22276, 22276,\n",
       "         22276, 16309, 16309, 16309, 16309, 16309, 16309, 13211, 13987,\n",
       "         13987, 13987, 13987, 13987, 13987, 13987, 18337, 18337, 18337,\n",
       "          3868,  3868,  7070,  7070,  7070,  7070,  7070,  7070, 22861,\n",
       "         16106, 16106, 16106, 16106, 16106, 16106,  6739,  6739,  6739,\n",
       "          6739, 10316, 24067, 24067, 10316, 10316, 19149, 19149, 19149],\n",
       "        [16189, 23019, 23019, 28517,  3087,  3087,  3087,  3087, 15697,\n",
       "         15697, 15697, 14464, 12955, 12955, 12955, 12955, 12955, 14925,\n",
       "         14925, 14925, 14925, 14925, 15931, 15931, 12072,  6548,  6548,\n",
       "          6548,  6548, 20171,  2552,  2552,  2552, 21729, 21729, 21729,\n",
       "         21729,  9259,  9259,  9259,  9259, 11403, 11403, 22190, 22190,\n",
       "          4253,  4253,  4253,  4253,  2747, 28256, 28256, 28256, 22408,\n",
       "         22408, 22408, 22408, 13579, 13579, 13579, 12908, 12908, 12908,\n",
       "         15242, 15242, 18111, 18111, 18111, 18111, 18111,  1402,  1402],\n",
       "        [ 4141,  4141,  4141,  1786,  1786,  1786,  1786,     9,     9,\n",
       "             9,     9,     9,     9,     9, 26987, 31981, 31981, 31981,\n",
       "         31981, 31981, 31981, 16283, 16283, 16283, 22246, 22246, 29771,\n",
       "         29771, 29771, 29771, 29771, 11799, 11799, 11799, 11799, 11799,\n",
       "         11799, 11799, 11799, 11799, 11799, 13302, 13302, 11799, 13302,\n",
       "         13302, 13302, 16873, 16873, 16873, 16873, 16873, 16873, 18287,\n",
       "         18287, 18287, 18287, 30304, 30304, 30304, 30304, 30304,  1059,\n",
       "          1059,  1059,  1059,  1059,  1059,  1059,  1059,  1059,  1059],\n",
       "        [16982,  1626,  1626,  1626,  1626,  1626,  1626,  1626, 23437,\n",
       "         23437, 23437, 23437, 23437,  6178,  6178,  6178, 17968, 11073,\n",
       "         11073,  2610,  2610,  2610, 30654, 12390, 12390, 12390, 12390,\n",
       "         22206, 22206, 22206, 22206,  6407,  6407,  4451, 31913, 31913,\n",
       "         31913,  4345,  4345,  4345, 30645,  2886,  2886, 25940, 25940,\n",
       "         25940, 25940, 29557,  1506,  1506,  1506,  1506,  1506, 19394,\n",
       "         19394, 19394, 11319, 11319, 11319, 11319, 24386, 24386, 24386,\n",
       "         26563, 26563, 22545, 22545, 24801,  6873,  6873,  6873, 11649],\n",
       "        [ 2735, 25948, 25948, 28556, 28556, 28556, 28556, 28556, 28556,\n",
       "         23269, 23269, 23269, 18330, 18330, 18330, 18330, 18330, 21782,\n",
       "         21782, 21782, 21782,  1174,  1174,  1174, 11998, 11998, 11998,\n",
       "          7060,  7060, 12857,   985, 12857,  9522,  9522,  9522,  9522,\n",
       "         20771, 20771, 20771, 20771, 11531, 24183, 24183, 24183, 15783,\n",
       "         15783, 12165, 12165, 12165, 12165, 12165, 19811, 19811, 19811,\n",
       "         19811, 19811, 25040, 25040, 25040, 25040, 25040,  8392,  8392,\n",
       "         15791, 15791, 13570, 13570, 13570, 13570, 13570, 13570, 13570],\n",
       "        [14876, 14876, 14876, 19586,  4303,  4303,  4303,  4303,  4303,\n",
       "          4303,  4303,  4303,  1854,   274,   274,   274,   274,  6251,\n",
       "         28656, 28656, 28656, 28656, 28656, 28656, 28656, 16928, 16928,\n",
       "         16928, 16928, 16928, 25953, 25953, 30887, 30887, 30887, 30887,\n",
       "         30887, 30887, 30887, 30887, 30887, 30887, 30466, 30466, 30466,\n",
       "         30466, 30466, 30466,  3433,  3433,  3433,  3433, 12081, 12081,\n",
       "         12081, 12081, 11149,  2248,  2248,  2248,  4359,  4359,  4359,\n",
       "          4359,  4359,  4359, 28193, 28193, 28193, 28193, 28193,  3297],\n",
       "        [ 5451,  5451,  5451, 19000, 19000, 19000, 19000, 18801,  2606,\n",
       "          2606,  7981,  7981,  7981,  7981,  7981,   908,   908,   908,\n",
       "         28816, 28816, 28816, 28816, 28816, 28816,  8319,  8319,   199,\n",
       "           199,   199,   199, 17355, 17355, 17355, 17355, 17355, 17355,\n",
       "         17355,  1227,  5802, 30287, 30287, 30287, 30287, 30287, 29201,\n",
       "         29201, 24617, 24617, 24617, 10626, 10626, 10626, 23183, 23183,\n",
       "         23183, 23183, 13665, 13665, 13665, 13665, 13665, 24439, 24439,\n",
       "          6512,  6512,  6512, 15533, 15533, 15533, 15533, 11103, 11103],\n",
       "        [17668, 17668, 17668, 15000, 15000, 15000, 17241, 17241, 17241,\n",
       "         17241,  3304,  3304,  3304,  3304, 26052, 26052, 26052, 18177,\n",
       "         18177,  1224,  1224,  1224, 26627, 26627, 26627, 26627, 13620,\n",
       "         29626, 29626, 29626, 29626, 21084, 10496, 21084, 28901, 28901,\n",
       "         28901, 31169, 31169, 31169, 31169,  9954, 21852, 13957, 13957,\n",
       "         13957, 13957, 27495, 27495, 27495,  5154,  5154,  5154,  5154,\n",
       "          5154, 23980, 13425, 13425, 13425, 13425, 13425, 15938, 15938,\n",
       "          7135, 20449, 20449,  2820,  2820,  2820, 22323, 14889, 14889]],\n",
       "       dtype=int32), 10.3737135, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:39<00:00,  1.78it/s, accuracy=0.241, cost=4.66]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.82it/s, accuracy=0.29, cost=4.01] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.467625, training avg acc 0.191054\n",
      "epoch 1, testing avg loss 4.476970, testing avg acc 0.260350\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:40<00:00,  1.78it/s, accuracy=0.436, cost=3.15]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.441, cost=3.2] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.680522, training avg acc 0.361675\n",
      "epoch 2, testing avg loss 3.204182, testing avg acc 0.428297\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  70%|███████   | 1100/1563 [10:14<04:18,  1.79it/s, accuracy=0.486, cost=2.68]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:38<00:00,  1.78it/s, accuracy=0.615, cost=1.78]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.93it/s, accuracy=0.511, cost=2.48]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.121251, training avg acc 0.568637\n",
      "epoch 5, testing avg loss 2.641959, testing avg acc 0.509167\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  25%|██▌       | 398/1563 [03:41<10:33,  1.84it/s, accuracy=0.589, cost=1.96]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:38<00:00,  1.78it/s, accuracy=0.86, cost=0.521] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.92it/s, accuracy=0.495, cost=3.18]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.971040, training avg acc 0.755977\n",
      "epoch 15, testing avg loss 3.509858, testing avg acc 0.476372\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:38<00:00,  1.78it/s, accuracy=0.883, cost=0.455]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.88it/s, accuracy=0.516, cost=3.11]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.905484, training avg acc 0.769010\n",
      "epoch 16, testing avg loss 3.560487, testing avg acc 0.488758\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:37<00:00,  1.78it/s, accuracy=0.862, cost=0.513]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.92it/s, accuracy=0.522, cost=3.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.867608, training avg acc 0.775671\n",
      "epoch 17, testing avg loss 3.741508, testing avg acc 0.483750\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:38<00:00,  1.78it/s, accuracy=0.87, cost=0.489] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.85it/s, accuracy=0.538, cost=3.26]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.837568, training avg acc 0.780742\n",
      "epoch 18, testing avg loss 3.807950, testing avg acc 0.476821\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:38<00:00,  1.78it/s, accuracy=0.872, cost=0.448]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.495, cost=3.5] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.793709, training avg acc 0.789968\n",
      "epoch 19, testing avg loss 3.965355, testing avg acc 0.465833\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:17<00:00,  1.82it/s, accuracy=0.891, cost=0.371]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.84it/s, accuracy=0.495, cost=3.35]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.756807, training avg acc 0.797308\n",
      "epoch 20, testing avg loss 3.924650, testing avg acc 0.471244\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:26<00:00,  1.50it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.17586066"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
